# import project.views
import datetime
import json
import shutil
import os

import jwt
from django.http import HttpResponse, JsonResponse

from jwt import PyJWTError

from .crl import GetNamespace,GetLastTime,DeleteNamespace,CreateNamespace,CreateDeploy,CreateService
from .crl import GetToken,CpLocalToPod
from .models import *
from .serializers import *

from apscheduler.scheduler import Scheduler

# 实例化
sched = Scheduler()


@sched.interval_schedule(seconds=30)
def updateEditTime():
    for pro in Project.objects.all():
        edittime = GetLastTime(pro.id, pro.id)
        if edittime is not None:
            pro.edittime = edittime + datetime.timedelta(hours=8)
            pro.save()


@sched.interval_schedule(seconds=300)
def sched_test():
    for pro in Project.objects.all():
        if pro.edittime + datetime.timedelta(minutes=30) < datetime.datetime.now():
            DeleteNamespace(pro.id)


sched.start()


def AllProjects(request):
    projects = Project.objects.filter(ispublic=True).order_by('-folks')
    try:
        token = request.GET.get("token")
        user = jwt.decode(token, '79846517984651ryvgubhnj', algorithms=['HS256'])
        for project in projects:
            project.isstar = IsStar(user["id"], project.id)
    except PyJWTError:
        for project in projects:
            project.isstar = False
    res = ProjectSerializer(projects)
    return JsonResponse(res, safe=False)


def GetUsers(request):
    try:
        token = request.GET.get("token")
        user = jwt.decode(token, '79846517984651ryvgubhnj', algorithms=['HS256'])
    except PyJWTError:
        return HttpResponse(status=401, content="请重新登录")
    projects = Project.objects.filter(user_id=user["id"])
    for project in projects:
        project.isstar = IsStar(user["id"], project.id)
    res = ProjectSerializer(projects)
    return JsonResponse(res, safe=False)


def GetExamples(request):
    projects = []
    for pro in Examples.objects.all():
        projects.append(Project.objects.get(id = pro.project_id))
    res = ProjectSerializer(projects)
    return JsonResponse(res,safe=False)

def GetProjectsStar(request):
    try:
        token = request.GET.get("token")
        user = jwt.decode(token, '79846517984651ryvgubhnj', algorithms=['HS256'])
    except PyJWTError:
        return HttpResponse(status=401, content="请重新登录")
    projectids = StarsPro.objects.filter(user_id=user["id"])
    projects = []
    for pro in projectids:
        projects.append(Project.objects.get(pk=pro.project_id))
    for project in projects:
        project.isstar = True
    res = ProjectSerializer(projects)
    return JsonResponse(res, safe=False)


def IsStar(user_id, project_id):
    if len(StarsPro.objects.filter(user_id=user_id, project_id=project_id)) != 0:
        return True
    return False


def CreateProject(request):
    if request.method == 'POST':
        body = json.loads(request.body)
        name = body["name"]
        introduction = ""
        if "introduction" in body and body["introduction"] is not None:
            introduction = body["introduction"]
        image = body["image"]
        token = body["token"]
        print(name)
        try:
            user = jwt.decode(token, '79846517984651ryvgubhnj', algorithms=['HS256'])
        except PyJWTError:
            return HttpResponse(status=401, content="请重新登录")

        project = Project(name=name, introduction=introduction, image_id=image, user_id=user["id"],
                          edittime=datetime.datetime.now())
        print(project.introduction)
        project.save()
        res = ProjectSerializer(project)
        return JsonResponse(res)


def EditProject(request):
    if request.method == 'POST':
        body = json.loads(request.body)
        id = body["id"]
        name = body["name"]
        introduction = ""
        if "introduction" in body and body["introduction"] is not None:
            introduction = body["introduction"]
        image = body["image"]

        res = CheckUserProject(body["token"], id)
        if type(res) != Project:
            return res
        project = res

        project.name = name
        project.introduction = introduction
        if project.image_id != image:
            project.image_id = image
            DeleteNamespace(id)
        project.save()
        return HttpResponse(project)


def DeleteProject(request):
    body = json.loads(request.body)
    id = body["id"]
    print(id)
    res = CheckUserProject(body["token"], id)
    if type(res) != Project:
        return res
    project = res
    DeleteNamespace(id)

    project.delete()
    if os.path.exists("/root/data/" + str(id)):
        shutil.rmtree("/root/data/" + str(id))
    if os.path.exists("/usr/local/nginx/html/data/"+ str(id)):
        shutil.rmtree("/usr/local/nginx/html/data/" + str(id))

    return HttpResponse()


def GotoProject(request):
    id = request.GET.get("id")
    res = CheckUserProject(request.GET.get("token"), id)
    if type(res) != Project:
        return res
    pro = res
    pro.views += 1
    pro.save()
    if GetNamespace(id) is None:
        CreateNamespace(id)
        CreateDeploy(id, id, pro.image.name)

        CreateService(id, id)
        CpLocalToPod(id)

    res = GetToken(id, id)
    return JsonResponse(res)


# 获取项目的基本信息
def GetProject(request):
    id = request.GET.get("id")
    pro = Project.objects.filter(id=id)
    if len(pro) == 0:
        return HttpResponse("项目不存在", status=202)
    pro = pro[0]
    if not pro.ispublic:
        try:
            user = jwt.decode(request.GET.get("token"), '79846517984651ryvgubhnj', algorithms=['HS256'])
            pro.isstar = IsStar(user["id"],pro.id)
        except PyJWTError:
            return HttpResponse(status=401, content="请重新登录")

    pro = ProjectSerializer(pro)
    return JsonResponse(pro)


def test(request):
    id = request.GET.get("id")
    return HttpResponse(GetLastTime(id, id))


# 如果失败返回错误信息，成功返回project
def CheckUserProject(token, id):
    try:
        user = jwt.decode(token, '79846517984651ryvgubhnj', algorithms=['HS256'])
    except PyJWTError:
        return HttpResponse(status=401, content="请重新登录")
    project = Project.objects.filter(id=id)
    if len(project) == 0:
        return HttpResponse("项目不存在", status=202)
    project = project[0]
    if project.user.username != user["username"]:
        return HttpResponse("不是您的项目，您可以克隆后运行", status=202)
    return project
